const Collect = require("../models/collect");
const Food = require("../models/food");
const Sports = require("../models/sports");
const Topic = require("../models/topic");

exports.isCollect = async function (userId, id, collectType) {
  const collect = await Collect.findOne({
    where: {
      userId,
      collectId: id,
      collectType,
    },
  });
  if (collect) {
    return true;
  } else {
    return false;
  }
};

// 收藏文章或者食物或运动
exports.collect = async function (userId, collectType, id) {
  return Collect.create({
    userId,
    collectType,
    collectId: id,
  });
};
exports.uncollect = async function (userId, collectType, id) {
  await Collect.destroy({
    where: {
      userId,
      collectId: id,
      collectType,
    },
    individualHooks: true,
  });
};
//获取收藏食物
exports.collectFood = async function (userId) {
  return Collect.findAll({
    where: { userId, collectType: "food" },
    attributes: ["id"],
    include: {
      model: Food,
      attributes: [
        "id",
        "img",
        "name",
        "heat_cal",
        "碳水化合物(克)",
        "脂肪(克)",
        "蛋白质(克)",
      ],
      as: "food",
    },
  });
};

//获取收藏运动
exports.collectSports = async function (userId) {
  return Collect.findAll({
    where: { userId, collectType: "sports" },
    attributes: ["id"],
    include: {
      model: Sports,
      attributes: ["id", "img", "name", "heat"],
      as: "sports",
    },
  });
};

//获取收藏列表
exports.getList = async function (userId) {
  const topicArr = await Collect.findAll({
    where: { userId, collectType: "topic" },
    attributes: ["id"],
    include: {
      model: Topic,
      attributes: ["id", "title", "img", "readNum"],
      as: "topic",
    },
  });

  return topicArr;
};
